package com.estock.platform.http.request;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.estock.common.model.security.Index;
import com.estock.common.model.security.Stock;
import com.estock.common.model.security.enums.StockType;

/**
 * @author richard
 *
 */
public class StockClientRequest extends BaseClientRequest{
	
    protected StockClientRequest(String url) {
    	super(url);
    }
    
	public static SinaJSRequestBuilder getSinaJSRequestBuilder(String url) {
        return new SinaJSRequestBuilder(url);
    }
	
	public static YahooCsvRequestBuilder getYahooCsvRequestBuilder(String url) {
        return new YahooCsvRequestBuilder(url);
    }
	
	public static class SinaJSRequestBuilder extends StockRequestBuilder {
        public SinaJSRequestBuilder(String url) {
            super(url);
        }
        
        public SinaJSRequestBuilder appendBulkStocks(List<Stock> stocks) {
        	for (Stock stock : stocks) {
        		this.url += StockType.getAbbrByStockType(stock.getType()).toLowerCase() + stock.getCode();
        		this.url += ",";
        	}
            return this;
        }
        
        public SinaJSRequestBuilder appendBulkIndexes(List<Index> indexes) {
        	for (Index index : indexes) {
        		this.url += StockType.getAbbrByStockType(index.getType()).toLowerCase() + index.getCode();
        		this.url += ",";
        	}
            return this;
        }
    }
	
	public static class YahooCsvRequestBuilder extends StockRequestBuilder {
        public YahooCsvRequestBuilder(String url) {
            super(url);
            // time period: d=day
            this.parameters.put("g", "d");
            this.parameters.put("ignore", ".csv");
        }

        public YahooCsvRequestBuilder appendStockCodeAndType(String code, int type) {
        	String abbr = StockType.getAbbrByStockType(type).toUpperCase();
        	this.parameters.put("s", code + "." + 
        			(StringUtils.equals(abbr, StockType.SH.name()) ? "SS" : "SZ"));
            return this;
        }
        
        public YahooCsvRequestBuilder appendDateRange(Date latestDateWithPrice) {
        	Calendar car = Calendar.getInstance();
        	car.setTime(latestDateWithPrice);
        	
        	this.parameters.put("a", car.get(Calendar.MONTH));
        	this.parameters.put("b", car.get(Calendar.DAY_OF_MONTH));
        	this.parameters.put("c", car.get(Calendar.YEAR));
            return this;
        }
       
    }
	
}
